package com.example.demotest.controller;

import com.example.demotest.pojo.ResponseMessage;
import com.example.demotest.service.ProductFavoriteService;
import com.example.demotest.service.ProductService;
import com.example.demotest.util.JWT;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/products/favorite")
public class ProductFavoriteController {

    @Autowired
    private ProductFavoriteService productFavoriteService;

    @Autowired
    private JWT jwt;

    /**
     * 收藏某商品
     */
    @PostMapping("/{productId}")
    public ResponseMessage<String> addFavorite(HttpServletRequest request, @PathVariable Integer productId) {
        String token = jwt.extractToken(request);
        if (token == null || !jwt.validateToken(token)) {
            return ResponseMessage.error(401,"请先登录");
        }

        Integer userId = jwt.getUserIdFromToken(token);
        productFavoriteService.addProductFavorite(userId,productId);
        return ResponseMessage.success("收藏成功");
    }

    /**
     * 取消收藏
     */
    @DeleteMapping("/{productId}")
    public ResponseMessage<String> removeFavorite(HttpServletRequest request, @PathVariable Integer productId) {
        String token = jwt.extractToken(request);
        if (token == null || !jwt.validateToken(token)) {
            return ResponseMessage.error(401, "请先登录");
        }

        Integer userId = jwt.getUserIdFromToken(token);
        productFavoriteService.removeProductFavorite(userId, productId);
        return ResponseMessage.success("取消收藏成功");
    }

    /**
     * 获取我的收藏列表
     */
    @GetMapping("/favorites")
    public ResponseMessage<?> getMyFavorites(HttpServletRequest request) {
        String token = jwt.extractToken(request);
        if (token == null || !jwt.validateToken(token)) {
            return ResponseMessage.error(401, "请先登录");
        }

        Integer userId = jwt.getUserIdFromToken(token);
        return ResponseMessage.success(productFavoriteService.getFavoritesByUserId(userId));
    }

    /**
     * 查询当前用户是否收藏了某商品
     */
    @GetMapping("/check")
    public ResponseMessage<Boolean> checkIfFavorited(HttpServletRequest request,
                                                     @RequestParam Integer productId) {
        String token = jwt.extractToken(request);
        if (token == null || !jwt.validateToken(token)) {
            return ResponseMessage.error(401, "请先登录");
        }

        Integer userId = jwt.getUserIdFromToken(token);

        boolean isFavorited = productFavoriteService.isProductFavorited(userId, productId);
        return ResponseMessage.success(isFavorited);
    }
}
